package org.example.controller;

import org.example.entity.User;
import org.example.repository.UserRepository;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 认证控制器
 */
@RestController
@RequestMapping("/auth")
@CrossOrigin(origins = "*")
public class AuthController {
    
    @Autowired
    private UserService userService;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginRequest request) {
        try {
            // 根据用户名或邮箱查找用户
            Optional<User> userOpt = userService.findByUsernameOrEmail(request.getUsername(), request.getUsername());
            
            if (userOpt.isEmpty()) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid username or password");
            }

            User user = userOpt.get();

            // 验证密码
            if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid username or password");
            }

            // 检查用户状态
            if (user.getStatus() == 0) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Account disabled");
            }

            // 更新最后登录时间（使用北京时间）
            user.setUpdatedAt(LocalDateTime.now(java.time.ZoneId.of("Asia/Shanghai")));
            userRepository.save(user);

            // 返回用户信息（不包含密码）
            user.setPassword(null);
            
            // 根据用户角色确定登录后的页面路径
            String userRole = user.getRole();
            if (userRole == null || userRole.isEmpty()) {
                userRole = "USER"; // 默认为普通用户
                user.setRole(userRole);
                userRepository.save(user); // 更新用户角色
            }
            
            String redirectPath = getRedirectPathByRole(userRole);
            
            Map<String, Object> response = new HashMap<>();
            response.put("user", user);
            response.put("message", "Login successful");
            response.put("redirectPath", redirectPath);
            response.put("userRole", userRole);
            response.put("roleDescription", getRoleDescription(userRole));
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Login failed: " + e.getMessage());
        }
    }
    
    /**
     * 用户注册
     */
    @PostMapping("/register")
    public ResponseEntity<?> register(@Valid @RequestBody RegisterRequest request) {
        try {
            User user = new User();
            user.setUsername(request.getUsername());
            user.setPassword(request.getPassword());
            user.setEmail(request.getEmail());
            user.setNickname(request.getNickname());
            user.setPhone(request.getPhone());
            // 注册时固定为普通用户，管理员只能通过数据库直接创建
            user.setRole("USER");
            
            User createdUser = userService.createUser(user);
            createdUser.setPassword(null); // 不返回密码
            
            Map<String, Object> response = new HashMap<>();
            response.put("user", createdUser);
            response.put("message", "注册成功");
            
            return ResponseEntity.status(HttpStatus.CREATED).body(response);
            
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    /**
     * 检查用户名是否可用
     */
    @GetMapping("/check-username")
    public ResponseEntity<?> checkUsername(@RequestParam String username) {
        try {
            Optional<User> user = userService.findByUsername(username);
            Map<String, Object> response = new HashMap<>();
            response.put("available", user.isEmpty());
            response.put("message", user.isEmpty() ? "用户名可用" : "用户名已存在");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("检查失败：" + e.getMessage());
        }
    }
    
    /**
     * 检查邮箱是否可用
     */
    @GetMapping("/check-email")
    public ResponseEntity<?> checkEmail(@RequestParam String email) {
        try {
            Optional<User> user = userService.findByEmail(email);
            Map<String, Object> response = new HashMap<>();
            response.put("available", user.isEmpty());
            response.put("message", user.isEmpty() ? "邮箱可用" : "邮箱已存在");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("检查失败：" + e.getMessage());
        }
    }
    
    // 内部类用于请求体
    public static class LoginRequest {
        private String username;
        private String password;
        
        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }
        public String getPassword() { return password; }
        public void setPassword(String password) { this.password = password; }
    }
    
    public static class RegisterRequest {
        private String username;
        private String password;
        private String email;
        private String nickname;
        private String phone;
        
        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }
        public String getPassword() { return password; }
        public void setPassword(String password) { this.password = password; }
        public String getEmail() { return email; }
        public void setEmail(String email) { this.email = email; }
        public String getNickname() { return nickname; }
        public void setNickname(String nickname) { this.nickname = nickname; }
        public String getPhone() { return phone; }
        public void setPhone(String phone) { this.phone = phone; }
    }
    
    /**
     * 根据用户角色获取登录后的重定向路径
     */
    private String getRedirectPathByRole(String role) {
        switch (role) {
            case "ADMIN":
                return "/admin/dashboard";
            case "MAINTENANCE":
                return "/maintenance/dashboard";
            case "USER":
                return "/user/dashboard";
            default:
                return "/dashboard";
        }
    }
    
    /**
     * 获取角色描述
     */
    private String getRoleDescription(String role) {
        switch (role) {
            case "ADMIN":
                return "管理员";
            case "MAINTENANCE":
                return "维修师傅";
            case "USER":
                return "普通用户";
            default:
                return "未知角色";
        }
    }
}
